<?php

/**
 *   OPENSHOP  SMS 处理类
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: cls_sms.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      jeffjia
 */

if (!defined('IN_OS'))
{
    die('Access Denied');
}

class sms_baison {
	
    /**
     * 存放MYSQL对象
     *
     * @access  private
     * @var     object      $db
     */
    private $db = null;

    /**
     * 存放OS对象
     *
     * @access  private
     * @var     object      $os
     */
    private $os  = null;	

    /**
     * 存放EndPoint对象
     *
     * @access  private
     * @var     object      $os
     */    
    private $endPoint = '';

    /**
     * 存放WebService Client对象
     *
     * @access  private
     * @var     object      $client
     */    
    private $client = '';    

	function __construct() {
	   $this->sms_baison();
	}
	
    /**
     * 构造函数
     *
     * @access  public
     * @return  void
     */
    public function sms_baison()
    {
        /* 由于要包含init.php，所以这两个对象一定是存在的，因此直接赋值 */
        $this->db = $GLOBALS['db'];
        $this->os = $GLOBALS['os'];
    }	
	
    /**
     * 用来判断SMS Webservice 终端是否可用
     *
     * @param string $endpoint   //当前的webservice终端
     * @return boolean $result   //如果提供的webservice终端可用则返回true否则返回false
     */
    public function checkEndpointAvailabe($endpoint){
    	$flag = '';
        $opts = array(
                    'http'=>array(
                    'method'=>"GET",
                    'timeout'=>120
                    )
                );
        $context = @stream_context_create($opts);
       
        $result  = @file_get_contents($endpoint, false, $context);
       
        if ($result != '') {
        	$flag = 'true';
        }else{
        	$flag = 'false';
        } 
        return $flag;
    }
    
   /**
     * 初始化SMS的WebService服务
     */
    public function initWebService($endPoint){ 
    	if (stripos($endPoint, '?wsdl') === false){
    	   $endPoint .= "?WSDL";
    	} 
        $this->endPoint = $endPoint; 
        if ($this->endPoint != '') {
        	try { 
        	   $isAvailabe = $this->checkEndpointAvailabe($this->endPoint);
        	   if ($isAvailabe == 'true') {  
                    $this->client = @new SoapClient($this->endPoint,array('encoding' => 'utf-8'));   
        	   }else{
        	   	    return false;
        	   }
        	}catch(Exception $e){  
               return false;
        	}
        } 
        return true;
    }

    /**
     * 获得OSA WebService的终端接口,判断是否正确初始化数据交换 服务
     */    
    public function getOSAConfig(){
        $sql = 'SELECT value FROM ' . $this->os->table('shop_config').' WHERE code = "osa_domain"';
 		$result = $this->db->getOne($sql);
        return $result;   	
    }


    /**
     * 获得OSA 数据传输funcID :521411
     */    
    public function getOSAFuncId(){
        $sql = 'SELECT value FROM ' . $this->os->table('shop_config').' WHERE code = "osa_funcid"';
 		$result = $this->db->getOne($sql);
        return $result;   	
    }
     /**
     * 获得OSA 数据传输OSA_user
     */    
    public function getOSA_user(){
        $sql = 'SELECT value FROM ' . $this->os->table('shop_config').' WHERE code = "osa_user"';
 		$result = $this->db->getOne($sql);
        return $result;   	
    }

     /**
     * 获得OSA 数据传输OSA_PWD
     */    
    public function getOSA_pwd(){
        $sql = 'SELECT value FROM ' . $this->os->table('shop_config').' WHERE code = "osa_pwd"';
 		$result = $this->db->getOne($sql);
        return $result;   	
    }


   /**
     * 获得SMS WebService的终端接口,判断是否正确初始化SMS短信服务
     */    
    public function getSMSConfig(){
        $sql = 'SELECT value FROM ' . $this->os->table('shop_config').' WHERE code = "sms_domain"';
        $result = $this->db->getOne($sql);
        return $result;   	
    }

   /**
     * 获得SMS 账户设置状态
     */       
    public function getSMSAccountConfig(){
    	$sql = 'SELECT value FROM '.$this->os->table('shop_config').' WHERE code = "sms_user_name"';
    	$result = $this->db->getOne($sql);
    	return $result;
    } 

    // 获得SMS 账户密码
    public function getAccountPassword(){
        $sql = 'SELECT value FROM '.$this->os->table('shop_config').' WHERE code = "sms_password"';
        $result = $this->db->getOne($sql);
        //$key = 'openshop';
        //$result = $this->decrypt($t_result,$key);
        return $result;        
    }    
    
    // 设置SMS 账户新的密码
    public function setAccountNewPassword($newpassword){
        //$key = 'openshop';
        //$newpassword = $this->ecrypt($newPassword,$key);
    	$sql = "UPDATE ".$GLOBALS['os']->table('shop_config').
               "SET value = '".$newpassword."' WHERE code = 'sms_password'";
        $GLOBALS['db']->query($sql);    	
    }
    
    /**
     * 调用SMS WebService的AccountChangePassword接口来修改用户短信密码
     */   
    public function accountChangePassword($params){
    	$result = $this->client->__soapCall('AccountChangePassword',
    	                                    array("parameters"=>$params));
    	return $result->AccountChangePasswordResult;
    }

   /**
     * 调用SMS WebService的AccountBalanceQuery接口来查询用户短信账号余额
     */ 
    public function AccountBalanceQuery($params){
        $result = $this->client->__soapCall('AccountBalanceQuery',
                                            array("parameters"=>$params));
        return $result->AccountBalanceQueryResult;    	   
    }

   /**
     * 调用SMS WebService的QuerySMSStatus接口来查询用户短信发送状态
     */     
    public function querySMSStatus($params){
        $t_result = $this->client->__soapCall('QuerySMSStatus',
                                              array("parameters"=>$params));
        $result = array('code' => $t_result->QuerySMSStatusResult,
                        'status' => $t_result->status
                       );                                            
        return $result;         
    }    

   /**
     * 调用SMS WebService的SendSMS接口来发送用户短信
     */  
    public function sendSMS($params){
        $t_result = $this->client->__soapCall('SendSMS1',
                                            array("parameters"=>$params));
        $result = array('code' => $t_result->SendSMS1Result,
                        'message' => $t_result->strErrorMessage
                       );                                               
        return $result;       
    }

	 /**
     * 调用OSA WebService的osaDataDownLoad
     */  
	 public function osaDataDownLoad($user, $pwd, $funcid,$downid,$loadid,$tablename){
	 	$endpoint = $this->getOSAConfig();
		$result   = array(); 
        if ($endpoint != '' && eregi("\\.asmx$", $endpoint)) {
			 try{
                if($this->initWebService($endpoint)){
    	    		$param = array(
                    		     'user' =>  $this->getOSA_user(),
                          		 'pwd' =>  $this->getOSA_pwd(),
                                 'funcid' =>  $this->getOSAFuncId(),
                         		 'downid' => $downid,  //下载
                           		 'loadid' => $loadid,	//上传
                         		); 
                	   $t_result = $this->client->__soapCall('OSATransport',
                    			                            array("parameters"=>$param));  
	                    if( $t_result->OSATransportResult===1) 
	                    {
	                    	$result = array('code' => 1,
	                    		        'message' => $tablename.'数据执行成功'
	                           			); 
	                    }
	                    else { 
	                    		$result = array('code' =>0,
	                    		        'message' => $downid,$tablename.'数据执行失败'
	                           			); 
	                    }
            		
				}else{
                	$result = array('code' => -1002,
                    	            'message' => '初始化服务出错'
                           			);
				}   
            }catch(Exception $e){
                $result = array('code' => -1002,
                                'message' => '初始化服务出错'
                           );
            }       
		}
		 return $result;     
	 }

    /**
     * 调用后台短信平台的webservice接口来发送短信
     *
     * @param $string $tagetNumber   // 要发送的手机号码
     * @param $string $msg_content   // 要发送的短信内容
     * @param $string $sign_content  // 要发送的短信签名
     * @return array $result         // 返回结果用数组展示
     *                               // code = 发送短信ID(发送成功) message = 发送失败时的相关出错信息(code < 0)
     *                               // code = -1002 message = 初始化短信服务出错 
     *                               // code = -1001 message = 短信服务终端没有正确配置
     */
    public function sendMessage($tagetNumber,$msg_content,$sign_content){
    	$endpoint = $this->getSMSConfig();
    	$result   = array();
        if ($endpoint != '' && eregi("\\.asmx$", $endpoint)) {
            try{
                if($this->initWebService($endpoint)){
    	    		$param = array(
                    		     'ProductId' => 'OpenShop',
                          		 'UserId' => $this->getSMSAccountConfig(),
                                 'Password' => $this->getAccountPassword(),
                         		 'TargetNumber' => Encrypt_Phone(trim($tagetNumber)),
                           		 'MessageContent' => $msg_content,
                         	 	 'MessageSign' => $sign_content,
                          	 	 'PortNo' => '-1',
                         		 'InstructionId' => '-1',                                   
                         		 'StatusNotifyType' => '-1',
                         		 'StatusNotifyTarget' => ''  
                         		);
            		$t_result = $this->client->__soapCall('SendSMS1',
                    			                            array("parameters"=>$param));
            		$result = array('code' => $t_result->SendSMS1Result,
                    		        'message' => $t_result->strErrorMessage
                           			);
				}else{
                	$result = array('code' => -1002,
                    	            'message' => '初始化短信服务出错'
                           			);
				}   
            }catch(Exception $e){
                $result = array('code' => -1002,
                                'message' => '初始化短信服务出错'
                           );
            }            	

        }else{
            $result = array('code' => -1001,
                            'message' => '短信服务终端没有正确配置'
                           );        	
        }
        return $result;                                                	
    }
    
    /**
     * 获得内置信息列表
     *
     * @param   string  $infoType            内置信息类型 - 0:内置短信 1:内置签名 
     * @return  array   $buildInfoList       查询成功返回的内置信息列表
     */    
    public function getBuildInfoList($infoType){
        /* 查询条件 */
        $filter['keywords']     = empty($_REQUEST['keywords']) ? 0 : trim($_REQUEST['keywords']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keywords'] = json_str_iconv($filter['keywords']);
        }
        $filter['sort_by']      = empty($_REQUEST['sort_by']) ? 'create_time' : trim($_REQUEST['sort_by']);
        $filter['sort_order']   = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = (!empty($filter['keywords'])) ? " AND info_content LIKE '%" . mysql_like_quote($filter['keywords']) . "%' " : '';

        $sql = "SELECT count(*) FROM " .$GLOBALS['os']->table('sms_buildin_info'). " WHERE info_type = ".$infoType." $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        /* 获取信息数据 */
        $arr = array();
        $sql  = "SELECT * FROM " .$GLOBALS['os']->table('sms_buildin_info'). " WHERE info_type = ".$infoType." $where " .
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT ". $filter['start'] .", $filter[page_size]";
        $res  = $GLOBALS['db']->query($sql);

        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $row['create_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['create_time']);
            $arr[] = $row;
        }
        $filter['keywords'] = stripslashes($filter['keywords']);
        $arr = array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

        return $arr;
    }    
    
    // 设置短信账号的用户名
    public function setAccount($username){
        $sql = "UPDATE ".$GLOBALS['os']->table('shop_config').
               "SET value = '".$username."' WHERE code = 'sms_user_name'";
        $GLOBALS['db']->query($sql);
    }
    
    // 设置短信服务终端
    public function setEndpoint($endpoint){
        $sql = "UPDATE ".$GLOBALS['os']->table('shop_config').
               "SET value = '".$endpoint."' WHERE code = 'sms_domain'";
        $GLOBALS['db']->query($sql);    	
    }
    
    // 设置短信账号的密码
    public function setAccountPassword($password){
        //$key = 'openshop';
        //$password = $this->encrypt($password,$key);
    	$sql = "UPDATE ".$GLOBALS['os']->table('shop_config').
               "SET value = '".$password."' WHERE code = 'sms_password'";
        $GLOBALS['db']->query($sql);    	
    }
  
    // 简单加密算法用来保存用户密码
    private function encrypt($string, $key)
    {
        $result = '';
        for($i=1; $i<=strlen($string); $i++)
        {
            $char = substr($string, $i-1, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)+ord($keychar));
            $result.=$char;
        }
        return $result;
    }

    // 简单解密算法用来进行相关短信服务操作
    private function decrypt($string, $key)
    {
        $result = '';
        for($i=1; $i<=strlen($string); $i++)
        {
            $char = substr($string, $i-1, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)-ord($keychar));
            $result.=$char;
        }   
        return $result;
    }   
}

?>